import React, { useEffect, useState } from 'react';
import { Button, message, Modal, Tabs } from 'antd';
import { 
  FullscreenOutlined, 
  CloseOutlined, 
  ExclamationCircleOutlined 
} from '@ant-design/icons';
import WorkflowTimeline from './components/WorkflowTimeline';
import CancellationForm from './components/CancellationForm';
import { fetchCancellationData, saveCancellationData } from './service';
import { CancellationInfo, WorkflowData, PageState } from './types';
import { TabKey } from './constants';
import styles from './index.less';

const { TabPane } = Tabs;

// 初始状态
const initialState: PageState = {
  cancellationInfo: {
    projectId: '',
    projectName: '',
    approvalOpinion: '',
    changeType: '',
    changeReason: '',
    technicalUnitImpact: '',
    cancellationReason: '',
    attachments: []
  },
  workflow: {
    nodes: [],
    currentNode: 0
  },
  loading: false,
  activeTab: TabKey.BASIC_INFO
};

const ProjectCancellationPage: React.FC = () => {
  const [state, setState] = useState<PageState>(initialState);
  const [isFullscreen, setIsFullscreen] = useState<boolean>(false);

  // 初始化加载数据
  useEffect(() => {
    loadCancellationData();
  }, []);

  // 加载项目取消数据
  const loadCancellationData = async () => {
    setState(prev => ({ ...prev, loading: true }));
    try {
      const response = await fetchCancellationData();
      if (response.success && response.data) {
        const { data } = response;
        setState(prev => ({
          ...prev,
          cancellationInfo: {
            ...initialState.cancellationInfo,
            ...(data.cancellationInfo || {})
          },
          workflow: {
            ...initialState.workflow,
            ...(data.workflow || {})
          },
          loading: false
        }));
      } else {
        throw new Error(response.message || '获取数据失败');
      }
    } catch (error) {
      console.error('加载项目取消数据失败:', error);
      message.error('加载项目取消数据失败');
      setState(prev => ({ ...prev, loading: false }));
    }
  };

  // 处理关闭页面
  const handleClose = () => {
    Modal.confirm({
      title: '确认关闭',
      icon: <ExclamationCircleOutlined />,
      content: '关闭页面后，未保存的内容将丢失，是否确认关闭？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        // 这里可以添加关闭页面的逻辑，如跳转路由
        console.log('关闭页面');
      }
    });
  };

  // 处理表单字段变化
  const handleFormChange = (changedValues: Partial<CancellationInfo>) => {
    setState(prev => ({
      ...prev,
      cancellationInfo: {
        ...prev.cancellationInfo,
        ...changedValues
      }
    }));
  };

  // 处理选项卡切换
  const handleTabChange = (activeKey: string) => {
    setState(prev => ({
      ...prev,
      activeTab: activeKey
    }));
  };

  // 处理全屏切换
  const toggleFullscreen = () => {
    setIsFullscreen(!isFullscreen);
    // 实际项目中可以使用screenfull等库实现全屏功能
  };

  // 处理保存数据
  const handleSave = async () => {
    try {
      const result = await saveCancellationData(state.cancellationInfo);
      if (result.success) {
        message.success('保存成功');
      } else {
        message.error(result.message || '保存失败');
      }
    } catch (error) {
      console.error('保存失败:', error);
      message.error('保存失败');
    }
  };

  return (
    <div className={`${styles.container} ${isFullscreen ? styles.fullscreen : ''}`}>
      <div className={styles.header}>
        <h1 className={styles.title}>取消项目（新）</h1>
        <div className={styles['header-actions']}>
          <Button 
            type="text"
            icon={<FullscreenOutlined />}
            onClick={toggleFullscreen}
            className={styles['header-button']}
          />
          <Button 
            type="text"
            icon={<CloseOutlined />}
            onClick={handleClose}
            className={styles['header-button']}
          />
        </div>
      </div>
      
      <div className={styles['main-content']}>
        <div className={styles['left-panel']}>
          <WorkflowTimeline workflow={state.workflow} />
        </div>
        
        <div className={styles['right-panel']}>
          <Tabs 
            activeKey={state.activeTab}
            onChange={handleTabChange}
            className={styles.tabs}
          >
            <TabPane tab="查看完整流程图" key={TabKey.WORKFLOW_DIAGRAM}>
              <div className={styles['workflow-diagram']}>
                流程图展示区域（此处可根据实际需求实现）
              </div>
            </TabPane>
            <TabPane tab="基本信息" key={TabKey.BASIC_INFO}>
              <CancellationForm 
                cancellationInfo={state.cancellationInfo}
                onChange={handleFormChange}
                loading={state.loading}
              />
            </TabPane>
          </Tabs>
        </div>
      </div>
      
      <div className={styles['footer-mark']}>
        <div className={styles['mark-dot']}>!</div>
        <span>记录相关处理人</span>
      </div>
      
      <div className={styles['page-footer']}>
        <Button onClick={handleClose}>关闭</Button>
        <Button type="primary" onClick={handleSave}>保存</Button>
      </div>
    </div>
  );
};

export default ProjectCancellationPage;
